<template>
	<view>
<!--   <uni-nav-bar class="narBarHeader" backgroundColor="#03bcbf" color="#fff"   height="150rpx" :border="false" :fixed="true"  
                 leftWidth="200rpx">
              <template v-slot:left>
                  <span @click="back"  style="font-size: 30rpx;margin-top: 70rpx;" ><uni-icons type="back" size="28" color="#fff"></uni-icons></span>
              </template>
                 <template  ><div style="font-size: 35rpx;margin-top: 85rpx;width: 100%;margin-left: -56rpx;text-align: center;">{{zjtitle}}</div></template>
             </uni-nav-bar> -->
<scroll-view class="dialogue-box" :scroll-y="true"  :scroll-top="scrollTop" :style="{height:scrollViewHeight+'px'}">

  
		<view class="cu-chat dialogue-box-content" id="scroll-view-content">
      <view  class="" v-for="(item,index) in msgList" :key="index">
        <!-- AI消息 -->
        <view v-if="item.my == false"  class="cu-item aiitem" >
        	<view class="main aidia-box">   
        		<view class="content shadow aitxtbox " @click="copytxt(item.msg)">
        			<text class="aitxt">{{item.msg}}</text>
        		</view>
           <view v-if="item.id == '介绍' ? false : tool" class="operate">
              <view class="czbtn" @click="copytxt(item.msg)">复制</view>
              <!-- <view class="czbtn" @click="redact(item.msg)">编辑</view> -->
              <view class="czbtn" @click="gocontinue()">继续</view>
              <view class="czbtn" @click="retry">重试</view>
            </view>
        	</view>
        	<!-- <text class="text-blue" style="line-height: 100upx;"
        		>历史</text> -->
        </view>
          
        <!-- 用户消息 -->
        <view  v-if="item.my == true"  class="cu-item self" >
        	<view class="main yhxx">  
        		<view class="content bg-cyan shadow yhmsg" @click="">
        			<text>{{item.msg}}</text>
        		</view>
        	</view>
        	<image class="cu-avatar round" :src="headimg == '' ? 'https://www.iwangbang.com/skin/wx_mp_aixz/navigation/my.png' : headimg">
        </view>  
      </view>
		</view>
   </scroll-view>
    

		<view class=" cu-bar foot input" :style="[{bottom:inputBottom}]">
			<!-- <input  v-model="msg" class="solid padding-lr" :adjust-position="false" :focus="false" maxlength="1000"
				cursor-spacing="20" :placeholder="loading ? 'AI正在思考中，请稍后~' : prompted"
				  @confirm="sendMsg('mnst')"></input> -->
          <textarea class="asfasd padding-lr" v-model="msg" :style="{height: textheight,maxHeight:textmaxHeight}" :disable-default-padding='true'  name="" id="" cols="30" rows="10" :auto-height="fsddfsd" :fixed="true" @linechange="linechange" maxlength="-1" 
            @confirm="sendMsg" :placeholder="loading ? 'AI正在思考中，请稍后~' : prompted"cursor-spacing="20" :adjust-position="false" :focus="false" :show-confirm-bar='false'></textarea>
          
          
  
			<button class="cu-btn bg-cyan shadow" :disabled="loading" @click="sendMsg('mnst')">
				<text class="cuIcon-loading2 cuIconfont-spin" ></text>发送 
			</button>
		</view> 
    <aidialogue ref="aidialo" @backHome='backHome'></aidialogue>
	</view>
</template>   

<script>
  import  aidialogue  from '../../components/aichat/aichat.vue'
	export default {
    onLaunch:function(){
      console.log('000001');
    },
    
    onHide: function() {
    	console.log('111118')
    },
    components:{
      aidialogue
    },
		data() {
			return { 
        textheight:'120rpx',
        textmaxHeight:'120rpx',
        tautology:'',
				loading: false,
        aisse:"",
        msgList:[],
				msgContent: "",
				msg: "", 
				inputBottom: 0,
				bottomFuncShow: false,
				chatAsset: {},
				assetType: 'n',
				statusColor: 'text-red',
				statusTimer: null,
				msgLoading: false,
        usertxt:'',
        typedText:'',
        currentIndex:0,
        safe:0,
        fhtxt:'',
        scrollTop:0,//滚动条位置
        scrollViewHeight:0,//滚动视图的高度
        msgindex:0,
        tool:false,
        onfirst:0,
        dhid:'',
        zjtitle:'',
        jsid:'',
        headimg:'',
        prompted:'',
        aidh:true,
			}
		},
		computed: {
      
		},
 
		watch: {
            
		},
    onLoad(e){
      console.log(e,'88888888');
      console.log(e.text);
      if(e.text !== undefined) {
        e.text = JSON.parse(decodeURIComponent(e.text))
      }
      console.log(e.type);
      if(e.type !== undefined) {
        this.aidh = false
      }
      console.log(e);
      uni.setNavigationBarTitle({
        title:e.title
      })
      if(e.introduce !== undefined ) {
        this.msgList.push({
          msg:e.introduce,
          my:false,
          id:'介绍'
        })
      }
      this.prompted = e.description
      this.zjtitle = e.title
      this.jsid = e.id
      console.log(this.jsid,'111111');
      if(e.text !== undefined) {
           this.sendMsg(e.text)
           this.loading = true
      }
      console.log(uni.getStorageSync('wbyun_token'));
      uni.setStorageSync('wbyun_inviteCode',e.inviteCode)
      this.scrollToBottom()
    },
		 onShow() {
       this.getList() 
       this.headimg = uni.getStorageSync('wbyun_headimg')
       uni.getSystemInfo({
         success:(res)=> {
           console.log(res.safeArea,res.screenHeight);
         let tabBarHeight =  res.screenHeight - res.safeArea.bottom
         console.log(tabBarHeight);
         this.safe = tabBarHeight + 50
         console.log(this.safe,res.windowHeight);
         this.scrollViewHeight = res.windowHeight - 120
         console.log(this.scrollViewHeight);
         }
       })
        uni.onKeyboardHeightChange(res => {
          console.log(res);
          if(res.height !== 0) {
            this.inputBottom = res.height  +'px' 
            console.log(this.inputBottom,'1111');
          }else {
            this.inputBottom = res.height +'px'
          }
          
          console.log(res.height)
        })
		},

    
		onHide() { 

		}, 
    mounted() {
  
    },
		methods: {   
      getList() {
        console.log(this.jsid);
        if(this.aidh == false) return
         
        uni.request({
        	url: getApp().globalData.apiDomain+'airole/getinfo',
        	method: 'POST',
        	header: {
        		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
        		'token': uni.getStorageSync('wbyun_token'),
            'wbapp':'weixin_mp_xbgy'
        	},
        	data: {
          'id':this.jsid
        	},
        	dataType: 'json',
        	success:  res => {
            console.log(res);
        		if (res['data']['code'] == 200) {
                console.log(res.data);
                this.msgList.push({
                  msg:res.data.datas.description,
                  my:false,
                  id:'介绍'
                })
                // this.prompted = res.data.datas.description
        		}else { 
        			uni.showToast({
        				title: res['data']['msg'],
        				icon: 'none'
        			});
        		}
        	},
        	fail: () => {},
        	complete: () => {
        	}
        });
      },
			 sendMsg(e) {
         console.log(this.msgList);
         console.log(this.jsid,'1001001');
        
         if(uni.getStorageSync('wbyun_token')== null || uni.getStorageSync('wbyun_token')==''){
         	uni.navigateTo({
         		url:'/pagesA/tellogin/tellogin'
         	})
          return
         }
        console.log(e);
        if(e !== 'mnst') {
          this.msg = e
        }
     
       if(this.msg  == '') {
         uni.showToast({
         	title: '请先输入您的问题!',
         	icon: 'none'
         });
         return
       }
       let txt = ''
       this.tautology = this.msg
      txt = this.msg
      this.msg = ''
      this.loading = true
        this.msgList.push({
          msg:txt,
          my:true 
        })
        
        this.scrollToBottom()
        this.msgList.push({
          msg:'',
          my:false,
          id:'',
        })
        this.msgList.map((item,index)=> {
          if(index == this.msgList.length -1) { 
            const timer = setInterval(() => {
                  let text = '小猪正在思考中请稍等...'
                  item.msg += text[this.msgindex]
                  this.msgindex++; 
                  if(this.msgindex == text.length) {
                    this.msgindex = 0
                    clearInterval((timer))
                    return
                  }
            }, 50);
          }
        })
        this.tool = false
        this.currentIndex = 0
     
 if(this.msgList.length>3) {
   console.log('3333333333333333333');
   console.log(this.dhid);
           uni.request({
           	url: getApp().globalData.apiDomain+'ai/newchat',
           	method: 'POST',
           	header: {
           		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
           		'token': uni.getStorageSync('wbyun_token'),
               'wbapp':'weixin_mp_xbgy'
           	},
           	data: {
               'text': txt,
               'vpsoft':'ai_zrms',
               'stream': 'yes',
               'dhid':this.dhid
           	},
           	dataType: 'json',
           	success:  res => {
               console.log(res);
           		if (res['data']['code'] == 200) {
               this.$refs.aidialo.timer(res.data.datas.aid)
               let arr = this.msgList.length -1
               console.log(arr,'77777');
               this.msgList.map((item,index)=> {
                 if(index == arr) {
                   item.id = res.data.datas.aid
                 }
               })
               console.log(this.msgList);
                   
           			return;
           		}else if(res['data']['code'] == '100500') {
                 uni.showToast({
                 	title:res['data']['msg'],
                 	icon: 'none'
                 });
                 uni.setStorageSync('wbyun_token','');
                 uni.setStorageSync('wbyun_username','');
                 uni.setStorageSync('wbyun_headimg','');
                 uni.setStorageSync('wbyun_tel','');
                 uni.setStorageSync('wbyun_icode','');
                 uni.navigateTo({
                 	url:'/pagesA/tellogin/tellogin'
                 })
                 this.loading = false
               }else { 
                 console.log(this.msgList.length -1);
                 setTimeout(()=> {
                   this.msgList.map((item,index) => {
                     if(index == this.msgList.length -1) {
                       item.msg = res['data']['msg']
                     }
                   })
                   this.loading = false
                 },1500)
                 
           			uni.showToast({
           				title: res['data']['msg'],
           				icon: 'none'
           			});
           		}
           	},
           	fail: () => {},
           	complete: () => {
           	}
           });
         }else {
            console.log('2222222222222222222');
            
            uni.request({
            	url: getApp().globalData.apiDomain+'ai/newchat',
            	method: 'POST',   
            	header: {
            		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
            		'token': uni.getStorageSync('wbyun_token'),
                'wbapp':'weixin_mp_xbgy'
            	},
            	data: {
            		'text': txt,
                'vpsoft':'ai_zrms',
                'stream': 'yes',
                'jsid':this.jsid
            	},
            	dataType: 'json',
            	success:  res => {
                console.log(res);
            		if (res['data']['code'] == 200) {
                  this.$refs.aidialo.timer(res.data.datas.aid)
                  this.dhid = res.data.datas.dhid
                  console.log(this.dhid);
                  let arr = this.msgList.length -1
                  console.log(arr,'77777');
                  this.msgList.map((item,index)=> {
                    if(index == arr) {
                      item.id = res.data.datas.aid
                    }
                  })
                  console.log(this.msgList);
                 // this.msgList.push({
                 //   msg:'',
                 //   my:false,
                 //   id:res.data.datas.aid
                 // })
            
            			return;
            		}else if(res['data']['code'] == '100500') {
                  uni.showToast({
                  	title:res['data']['msg'],
                  	icon: 'none'
                  });
                  uni.setStorageSync('wbyun_token','');
                  uni.setStorageSync('wbyun_username','');
                  uni.setStorageSync('wbyun_headimg','');
                  uni.setStorageSync('wbyun_tel','');
                  uni.setStorageSync('wbyun_icode','');
                  uni.navigateTo({
                  	url:'/pagesA/tellogin/tellogin'
                  })
                  this.loading = false
                }else if(res['data']['code'] == '519') {
                  setTimeout(()=> {
                    this.msgList.map((item,index) => {
                      if(index == this.msgList.length -1) {
                        item.msg = res['data']['msg']
                      }
                    })
                    this.loading = false
                    uni.showToast({
                    	title: res['data']['msg'],
                    	icon: 'none',
                      duration: 5000
                    });
                    setTimeout(() => {
                      uni.navigateTo({
                        url:'/pagesB/subson/subson/apply'
                      })
                    },2000)
                    
                  },1500)
                  
                }else { 
                  console.log(this.msgList.length -1);
                  setTimeout(()=> {
                    this.msgList.map((item,index) => {
                      if(index == this.msgList.length -1) {
                        item.msg = res['data']['msg']
                      }
                    })
                    this.loading = false
                  },1500)
            			uni.showToast({
            				title: res['data']['msg'],
            				icon: 'none'
            			});
            		}
            	},
            	fail: () => {},
            	complete: () => {
            	}
            });
            
            
         }

        
         
			},
linechange(e) {
        console.log(e.detail);
         if(e.detail.lineCount == 1) {
           this.textheight = '120rpx'
           this.textmaxHeight = '120rpx'
        }else if(e.detail.lineCount == 2) {
          this.textheight = '120rpx'
          this.textmaxHeight= '120rpx'
        }else if(e.detail.lineCount == 3) {
          this.textheight = '157rpx'
          this.textmaxHeight= '157rpx'
        }else
        console.log(this.textheight);
      },
      backHome(e,id,k) {
        this.startTyping(e,id,k)
        this.typedText = e
        console.log('123');
        // this.onfirst = false
        this.onfirst+=1
      },
      startTyping(e,id,k) {
        console.log(e,id,k);
        console.log(this.onfirst);
        if(this.onfirst == 0) {
          
          this.msgList.map((item,index)=> {
            if(index==  this.msgList.length -1) {
              item.msg = ''
            }
          })
        }
        let text = e
        this.msgList.map(item => {
          const timer = setInterval(() => {
            if(item.id == id) {
   
              if(k == 'ok' && this.currentIndex == e.length) {
                this.tool = true
                this.onfirst = 0
                this.loading = false
                clearInterval(timer)
                return
              }else if(k == 'error' && this.currentIndex == e.length) {
                this.tool = true
                this.onfirst = 0
                this.loading = false
                clearInterval(timer)
                return
              }
              if(e[this.currentIndex] == undefined) {
                clearInterval(timer);
                return 
              }else {
           
                item.msg += text[this.currentIndex]
                this.currentIndex++; 
     
                this.scrollToBottom()
              }
              }
            
          }, 50);
        })
      
      },
      copytxt(e) {
        console.log(e);
        uni.setClipboardData({
        	data: e,
        	success: function () {
        		console.log('success');
            uni.showToast({
            	title: '复制成功！',
            	icon: 'none'
            });
        	}
        });
      },
      redact(e) {
        console.log(e);
        uni.navigateTo({
        	url: '/pages/redact/redact?txt='+ e
        })
      },
      retry(){
         
        this.loading = true
          this.msgList.push({
            msg:this.tautology,
            my:true 
          })
          this.scrollToBottom()
          this.msgList.push({
            msg:'',
            my:false,
            id:'',
          })
          this.msgList.map((item,index)=> {
            if(index == this.msgList.length -1) { 
              const timer = setInterval(() => {
                    let text = '小猪正在思考中请稍等...'
                    item.msg += text[this.msgindex]
                    this.msgindex++; 
                    if(this.msgindex == text.length) {
                      this.msgindex = 0
                      clearInterval((timer))
                      return
                    }
              }, 50);
            }
          })
          this.tool = false
          this.currentIndex = 0
          uni.request({
          	url: getApp().globalData.apiDomain+'ai/newchat',
          	method: 'POST',
          	header: {
          		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
          		'token': uni.getStorageSync('wbyun_token'),
              'wbapp':'weixin_mp_xbgy'
          	},
          	data: {
          		'text': this.tautology,
              'vpsoft':'ai_zrms',
              'stream': 'yes' 
          	},
          	dataType: 'json',
          	success:  res => {
              console.log(res);
          		if (res['data']['code'] == 200) {
                this.$refs.aidialo.timer(res.data.datas.aid)
                let arr = this.msgList.length -1
                console.log(arr,'77777');
                this.msgList.map((item,index)=> {
                  if(index == arr) {
                    item.id = res.data.datas.aid
                  }
                })
                console.log(this.msgList);
            
        
          			return;
          		}else if(res['data']['code'] == '100500') {
                uni.showToast({
                	title:res['data']['msg'],
                	icon: 'none'
                });
                uni.setStorageSync('wbyun_token', '');
                this.loading = false
              }else { 
                console.log(this.msgList.length -1);
                setTimeout(()=> {
                  this.msgList.map((item,index) => {
                    if(index == this.msgList.length -1) {
                      item.msg = res['data']['msg']
                    }
                  })
                  this.loading = false
                },1500)
                
          			uni.showToast({
          				title: res['data']['msg'],
          				icon: 'none'
          			});
          		}
          	},
          	fail: () => {},
          	complete: () => {
          	}
          });
        
        
      },
      gocontinue() {
        console.log(this.dhid);
        this.msgList.push({
          msg:'继续',
          my:true 
        })
        this.scrollToBottom()
        this.msgList.push({
          msg:'',
          my:false,
          id:'',
        })
        this.msgList.map((item,index)=> {
          if(index == this.msgList.length -1) { 
            const timer = setInterval(() => {
                  let text = '小猪正在思考中请稍等...'
                  item.msg += text[this.msgindex]
                  this.msgindex++; 
                  if(this.msgindex == text.length) {
                    this.msgindex = 0
                    clearInterval((timer))
                    return
                  }
            }, 50);
          }
        })
        this.tool = false
        this.currentIndex = 0
        uni.request({
        	url: getApp().globalData.apiDomain+'ai/newchat',
        	method: 'POST',
        	header: {
        		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
        		'token': uni.getStorageSync('wbyun_token'),
            'wbapp':'weixin_mp_xbgy'
        	},
        	data: {
        		'text': '继续',
            'vpsoft':'ai_zrms',
            'stream': 'yes',
            'dhid':this.dhid
        	},
        	dataType: 'json',
        	success:  res => {
            console.log(res);
        		if (res['data']['code'] == 200) {
            this.$refs.aidialo.timer(res.data.datas.aid)
            let arr = this.msgList.length -1
            console.log(arr,'77777');
            this.msgList.map((item,index)=> {
              if(index == arr) {
                item.id = res.data.datas.aid
              }
            })
            console.log(this.msgList);
                
        			return;
        		}else if(res['data']['code'] == '100500') {
              uni.showToast({
              	title:res['data']['msg'],
              	icon: 'none'
              });
              uni.setStorageSync('wbyun_token', '');
              this.loading = false
            }else { 
              console.log(this.msgList.length -1);
              setTimeout(()=> {
                this.msgList.map((item,index) => {
                  if(index == this.msgList.length -1) {
                    item.msg = res['data']['msg']
                  }
                })
                this.loading = false
              },1500)
              
        			uni.showToast({
        				title: res['data']['msg'],
        				icon: 'none'
        			});
        		}
        	},
        	fail: () => {},
        	complete: () => {
        	}
        });
        
      },
    scrollToBottom(){
          this.$nextTick(()=>{
            uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res)=>{
              let top = res.height-this.scrollViewHeight ;
              if(top>0){
                this.scrollTop=top;
              }
            }).exec()
          })
        },
    problem(e) {
      console.log(e);
      this.msg = e
    },
    back() {
            uni.navigateBack({
              delta:1
            })
          },

		
			
			
			eliminate() {
        console.log('999998');
			}
		}
	}
</script>

<style>
	page {
		padding-bottom: 200upx;
	}
  body {
    background-color: #f3f3f3 !important;
  }

	.cu-chat .chat-avatar.cu-avatar {
	    width: 62upx;
	    height: 62upx;
	}

	.cu-item:not(.first) {
		padding-bottom: 0upx;
	}
	.cu-item.sec {
		padding-top: 0upx;
	}
	.main .content {
		word-wrap: break-word;
	}
	.foot {
/* 		padding-top: 20upx;
		padding-bottom: 0upx !important;
    margin-bottom: 0 !important; */
    display: flex !important;
    margin-bottom: 0rpx !important;
   
	}
	.foot .cu-btn {
    width: 130rpx;
    height: 90rpx;
		margin-right: 20upx;
	}
	.foot .action.func {
		margin-left: 30upx;
	}
  
  .yhmsg>text {
    width: 100%;
  }
 .aidia-box {
   display: flex;
   
   flex-direction: column;
   
 }
 .operate {
   width: 100%;
   display: flex;
   justify-content: space-between;
 }
 .czbtn {
   width: 130rpx;
   height: 55rpx;
   display: flex;
   justify-content: center;
   align-items: center;
   background-color: #4193FE;
   border-radius: 10rpx;
   margin: 10rpx 0;
   color: #fff;
 }
/* .aidia-box {
   width: 100% !important;
 }
 .aitxtbox {
   width: 100% !important;
 }
 .aitxt {
   width: 100%;
 } */
.cu-chat .aiitem>.main {
	max-width: calc(100%);
	display: flex;
  justify-content: center;
	align-items: center;
 
}

 
.aiitem {
  display: flex;
  padding: 20rpx !important;
  
 }

 .aitxt {
   width:100%;
 }
.cu-bar {
  height: 180rpx;
  background-color: rgb(246,250,252) !important;
 
}
.padding-lr {
  /* height: 90rpx !important; */
   box-shadow: -10px -10px 50px 0px rgb(225 227 228);
}




.cu-chat .aiitem>.main {
  margin: 0;
}
.asfasd {
  flex: 1;
  margin: 0 20rpx;
  background-color: rgb(246,250,252);
  padding: 20rpx;
  font-size: 36rpx;
}
.bg-cyan {
  background-color:#4193FE;
}
</style>
